/**
 * 检查重复装备数据脚本
 */

const mysql = require('mysql2/promise');
require('dotenv').config({ path: './nestjs-app/.env' });

async function checkDuplicateEquipment() {
  try {
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST || '43.143.253.188',
      port: process.env.DB_PORT || 3306,
      user: process.env.DB_USER || 'nextjs',
      password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
      database: process.env.DB_NAME || 'nextjs',
      timezone: '+08:00'
    });

    console.log('🔍 检查重复装备数据...');
    
    // 1. 查找重复ID的装备
    const [duplicateIds] = await connection.execute(`
      SELECT id, COUNT(*) as count
      FROM equipment_base 
      GROUP BY id 
      HAVING COUNT(*) > 1
      ORDER BY id
    `);

    if (duplicateIds.length > 0) {
      console.log(`❌ 发现 ${duplicateIds.length} 个重复ID的装备:`);
      duplicateIds.forEach(dup => {
        console.log(`   ID=${dup.id} 重复 ${dup.count} 次`);
      });
    } else {
      console.log('✅ 没有发现重复ID的装备');
    }

    // 2. 查找重复名称的装备（所有类型）
    const [duplicateNames] = await connection.execute(`
      SELECT name, COUNT(*) as count, GROUP_CONCAT(CONCAT(id, ':', type, ':', base) ORDER BY id) as details
      FROM equipment_base 
      GROUP BY name 
      HAVING COUNT(*) > 1
      ORDER BY name
    `);

    if (duplicateNames.length > 0) {
      console.log(`\n❌ 发现 ${duplicateNames.length} 个重复名称的装备:`);
      
      for (const duplicate of duplicateNames) {
        console.log(`\n📋 名称: ${duplicate.name} (重复 ${duplicate.count} 次)`);
        console.log(`   详情: ${duplicate.details}`);
        
        // 获取详细信息
        const [details] = await connection.execute(`
          SELECT id, name, type, base, level 
          FROM equipment_base 
          WHERE name = ?
          ORDER BY id
        `, [duplicate.name]);
        
        details.forEach(equipment => {
          const typeName = getTypeName(equipment.type);
          const baseName = getBaseName(equipment.base);
          console.log(`    ID=${equipment.id}, 类型=${equipment.type}(${typeName}), 基础=${equipment.base}(${baseName}), 等级=${equipment.level}`);
        });
      }
    } else {
      console.log('✅ 没有发现重复名称的装备');
    }

    // 3. 检查头盔中的相似名称装备
    console.log('\n🔍 检查头盔中的相似名称装备...');
    const [helmets] = await connection.execute(`
      SELECT id, name, type, base, level
      FROM equipment_base 
      WHERE type = 1
      ORDER BY name
    `);

    const nameGroups = {};
    helmets.forEach(helmet => {
      const baseName = helmet.name.replace(/·[文武异]/, ''); // 移除职业后缀
      if (!nameGroups[baseName]) {
        nameGroups[baseName] = [];
      }
      nameGroups[baseName].push(helmet);
    });

    const potentialDuplicates = Object.keys(nameGroups).filter(name => nameGroups[name].length > 1);
    
    if (potentialDuplicates.length > 0) {
      console.log(`⚠️  发现 ${potentialDuplicates.length} 个相似名称的头盔组:`);
      
      potentialDuplicates.forEach(baseName => {
        console.log(`\n📋 基础名称: ${baseName}`);
        nameGroups[baseName].forEach(helmet => {
          const baseName2 = getBaseName(helmet.base);
          console.log(`    ID=${helmet.id}, 名称=${helmet.name}, 基础=${helmet.base}(${baseName2}), 等级=${helmet.level}`);
        });
      });
    } else {
      console.log('✅ 没有发现相似名称的头盔');
    }

    // 4. 检查是否有通用头盔和职业头盔重复
    console.log('\n🔍 检查通用头盔和职业头盔重复...');
    const genericHelmets = helmets.filter(helmet => 
      !helmet.name.includes('·武') && 
      !helmet.name.includes('·文') && 
      !helmet.name.includes('·异')
    );

    if (genericHelmets.length > 0) {
      console.log(`📊 通用头盔数量: ${genericHelmets.length}`);
      console.log('📋 通用头盔列表:');
      genericHelmets.forEach(helmet => {
        const baseName = getBaseName(helmet.base);
        console.log(`    ID=${helmet.id}, 名称=${helmet.name}, 基础=${helmet.base}(${baseName}), 等级=${helmet.level}`);
      });

      // 检查是否有对应的职业头盔
      console.log('\n🔍 检查对应的职业头盔:');
      genericHelmets.forEach(generic => {
        const baseName = generic.name.replace(/·[文武异]/, '');
        const [corresponding] = helmets.filter(helmet => 
          helmet.name.includes('·武') || 
          helmet.name.includes('·文') || 
          helmet.name.includes('·异')
        );

        if (corresponding) {
          console.log(`   通用头盔: ${generic.name} (ID=${generic.id})`);
          console.log(`   对应职业头盔: ${corresponding.name} (ID=${corresponding.id})`);
        }
      });
    }

    await connection.end();
  } catch (error) {
    console.error('❌ 检查失败:', error.message);
  }
}

function getTypeName(type) {
  const typeNames = {
    1: '头盔',
    2: '武器',
    3: '防具',
    4: '项链',
    5: '护腕',
    6: '鞋子'
  };
  return typeNames[type] || '未知';
}

function getBaseName(base) {
  const baseNames = {
    1: '武士',
    2: '文人',
    3: '异师'
  };
  return baseNames[base] || '未知';
}

checkDuplicateEquipment();
